<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>8. Errors and Exceptions 错误和异常 &mdash; Python v2.7 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7 documentation" href="../index.html" />
    <link rel="up" title="The Python Tutorial" href="index.html" />
    <link rel="next" title="9. Classes 类" href="classes.html" />
    <link rel="prev" title="7. Input and Output 输入和输出" href="inputoutput.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="classes.html" title="9. Classes 类"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="inputoutput.html" title="7. Input and Output 输入和输出"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="errors-and-exceptions">
<span id="tut-errors"></span><h1>8. Errors and Exceptions 错误和异常<a class="headerlink" href="#errors-and-exceptions" title="Permalink to this headline">¶</a></h1>
<p>Until now error messages haven&#8217;t been more than mentioned, but if you have tried
out the examples you have probably seen some.  There are (at least) two
distinguishable kinds of errors: <em>syntax errors</em> and <em>exceptions</em>.</p>
<p>至今为止还没有进一步的谈论过错误信息，不过在你已经试验过的那些例子中，
可能已经遇到过一些。Python 中（至少）有两种错误：语法错误和异常
（ <em>syntax errors</em> and <em>exceptions</em> ）。</p>
<div class="section" id="syntax-errors">
<span id="tut-syntaxerrors"></span><h2>8.1. Syntax Errors 语法错误<a class="headerlink" href="#syntax-errors" title="Permalink to this headline">¶</a></h2>
<p>Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:</p>
<p>语法错误，也称作解释错误，可能是学习 Python 的过程中最容易犯的</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="bp">True</span> <span class="k">print</span> <span class="s">&#39;Hello world&#39;</span>
<span class="go">  File &quot;&lt;stdin&gt;&quot;, line 1, in ?</span>
<span class="go">    while True print &#39;Hello world&#39;</span>
<span class="go">                   ^</span>
<span class="go">SyntaxError: invalid syntax</span>
</pre></div>
</div>
<p>The parser repeats the offending line and displays a little &#8216;arrow&#8217; pointing at
the earliest point in the line where the error was detected.  The error is
caused by (or at least detected at) the token <em>preceding</em> the arrow: in the
example, the error is detected at the keyword <a class="reference external" href="../reference/simple_stmts.html#print"><tt class="xref docutils literal"><span class="pre">print</span></tt></a>, since a colon
(<tt class="docutils literal"><span class="pre">':'</span></tt>) is missing before it.  File name and line number are printed so you
know where to look in case the input came from a script.</p>
<p>解析器会重复出错的行，并在行中最早发现的错误位置上显示一个小“箭头”。错误
（至少是被检测到的）就发生在箭头 <em>指向</em> 的位置。示例中的错误表现在关键字
<a class="reference external" href="../reference/simple_stmts.html#print"><tt class="xref docutils literal"><span class="pre">print</span></tt></a> 上，因为在它之前少了一个冒号（ <tt class="docutils literal"><span class="pre">':'</span></tt> ）。同时也会显示文件名和行号，
这样你就可以知道错误来自哪个脚本，什么位置。</p>
</div>
<div class="section" id="exceptions">
<span id="tut-exceptions"></span><h2>8.2. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<p>Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during execution
are called <em>exceptions</em> and are not unconditionally fatal: you will soon learn
how to handle them in Python programs.  Most exceptions are not handled by
programs, however, and result in error messages as shown here:</p>
<p>即使是在语法上完全正确的语句，尝试执行它的时候，也有可能会发生错误。在
程序运行中检测出的错误称之为异常，它通常不会导致致命的问题，你很快就会
学到如何在 Python 程序中控制它们。大多数异常不会由程序处理，而是显示一
个错误信息</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="mi">10</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ZeroDivisionError</span>: <span class="n-Identifier">integer division or modulo by zero</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">4</span> <span class="o">+</span> <span class="n">spam</span><span class="o">*</span><span class="mi">3</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">NameError</span>: <span class="n-Identifier">name &#39;spam&#39; is not defined</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;2&#39;</span> <span class="o">+</span> <span class="mi">2</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">TypeError</span>: <span class="n-Identifier">cannot concatenate &#39;str&#39; and &#39;int&#39; objects</span>
</pre></div>
</div>
<p>The last line of the error message indicates what happened. Exceptions come in
different types, and the type is printed as part of the message: the types in
the example are <a title="exceptions.ZeroDivisionError" class="reference external" href="../library/exceptions.html#exceptions.ZeroDivisionError"><tt class="xref docutils literal"><span class="pre">ZeroDivisionError</span></tt></a>, <a title="exceptions.NameError" class="reference external" href="../library/exceptions.html#exceptions.NameError"><tt class="xref docutils literal"><span class="pre">NameError</span></tt></a> and <a title="exceptions.TypeError" class="reference external" href="../library/exceptions.html#exceptions.TypeError"><tt class="xref docutils literal"><span class="pre">TypeError</span></tt></a>.
The string printed as the exception type is the name of the built-in exception
that occurred.  This is true for all built-in exceptions, but need not be true
for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).</p>
<p>错误信息的最后一行指出发生了什么错误。异常也有不同的类型，异常类型做为
错误信息的一部分显示出来：示例中的异常分别为 零除错误
（ <a title="exceptions.ZeroDivisionError" class="reference external" href="../library/exceptions.html#exceptions.ZeroDivisionError"><tt class="xref docutils literal"><span class="pre">ZeroDivisionError</span></tt></a> ） ，命名错误（ <tt class="xref docutils literal"><span class="pre">NameError`）</span> <span class="pre">和</span> <span class="pre">类型</span>
<span class="pre">错误（:exc:`TypeError</span></tt> ）。打印错误信息时，异常的类型作为异常的内置名
显示。对于所有的内置异常都是如此，不过用户自定义异常就不一定了（尽管这
是一个很有用的约定）。标准异常名是内置的标识（没有保留关键字）。</p>
<p>The rest of the line provides detail based on the type of exception and what
caused it.</p>
<p>这一行后一部分是关于该异常类型的详细说明，这意味着它的内容依赖于异常类型。</p>
<p>The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack
traceback listing source lines; however, it will not display lines read from
standard input.</p>
<p>错误信息的前半部分以堆栈的形式列出异常发生的位置。通常在堆栈中列出了源代码行，然而，来自标准输入的源码不会显示出来。</p>
<p><a class="reference external" href="../library/exceptions.html#bltin-exceptions"><em>Built-in Exceptions</em></a> lists the built-in exceptions and their meanings.</p>
<p><a class="reference external" href="../library/exceptions.html#bltin-exceptions"><em>Built-in Exceptions</em></a> 列出了内置异常和它们的含义。</p>
</div>
<div class="section" id="handling-exceptions">
<span id="tut-handling"></span><h2>8.3. Handling Exceptions 控制异常<a class="headerlink" href="#handling-exceptions" title="Permalink to this headline">¶</a></h2>
<p>It is possible to write programs that handle selected exceptions. Look at the
following example, which asks the user for input until a valid integer has been
entered, but allows the user to interrupt the program (using <tt class="docutils literal"><span class="pre">Control-C</span></tt> or
whatever the operating system supports); note that a user-generated interruption
is signalled by raising the <a title="exceptions.KeyboardInterrupt" class="reference external" href="../library/exceptions.html#exceptions.KeyboardInterrupt"><tt class="xref docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> exception. :</p>
<p>可以编写程序来控制已知的异常。参见下例，此示例要求用户输入信息，一直到
得到一个有效的整数为止，而且允许用户中断程序（使用 <tt class="docutils literal"><span class="pre">Control-C</span></tt> 或
其它什么操作系统支持的操作）；需要注意的是用户生成的中断会抛出
<a title="exceptions.KeyboardInterrupt" class="reference external" href="../library/exceptions.html#exceptions.KeyboardInterrupt"><tt class="xref docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> 异常。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">x</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">&quot;Please enter a number: &quot;</span><span class="p">))</span>
<span class="gp">... </span>        <span class="k">break</span>
<span class="gp">... </span>    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="s">&quot;Oops!  That was no valid number.  Try again...&quot;</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>The <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement works as follows.</p>
<p><a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句按如下方式工作。</p>
<ul>
<li><p class="first">First, the <em>try clause</em> (the statement(s) between the <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> and
<a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> keywords) is executed.</p>
<p>首先，执行 <em>try 子句</em> （在 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 和 <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 关键字之间的部分）。</p>
</li>
<li><p class="first">If no exception occurs, the <em>except clause</em> is skipped and execution of the
<a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement is finished.</p>
<p>如果没有异常发生， <em>except 子句</em> 在 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句执行完毕后就被忽略了。</p>
</li>
<li><p class="first">If an exception occurs during execution of the try clause, the rest of the
clause is skipped.  Then if its type matches the exception named after the
<a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> keyword, the except clause is executed, and then execution
continues after the <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement.</p>
<p>如果在 try 子句执行过程中发生了异常，那么该子句其余的部分就会被忽略。
如果异常匹配于 <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 关键字后面指定的异常类型，就执行对应的except子
句。然后继续执行 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句之后的代码。</p>
</li>
<li><p class="first">If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statements; if no handler is
found, it is an <em>unhandled exception</em> and execution stops with a message as
shown above.</p>
<p>如果发生了一个异常，在 except 子句中没有与之匹配的分支，它就会传递到
上一级 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句中。如果最终仍找不到对应的处理语句，它就成
为一个 <em>未处理异常</em> ，终止程序运行，显示提示信息。</p>
</li>
</ul>
<p>A <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement may have more than one except clause, to specify
handlers for different exceptions.  At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not
in other handlers of the same <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement.  An except clause may
name multiple exceptions as a parenthesized tuple, for example:</p>
<p>一个 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句可能包含多个 except 子句，分别指定处理不同的异
常。至多只会有一个分支被执行。异常处理程序只会处理对应的 try 子句中发
生的异常，在同一个 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句中，其他子句中发生的异常则不作处
理。一个except子句可以在括号中列出多个异常的名字，例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="o">...</span> <span class="k">except</span> <span class="p">(</span><span class="ne">RuntimeError</span><span class="p">,</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">NameError</span><span class="p">):</span>
<span class="o">...</span>     <span class="k">pass</span>
</pre></div>
</div>
<p>The last except clause may omit the exception name(s), to serve as a wildcard.
Use this with extreme caution, since it is easy to mask a real programming error
in this way!  It can also be used to print an error message and then re-raise
the exception (allowing a caller to handle the exception as well):</p>
<p>最后一个 except 子句可以省略异常名，把它当做一个通配项使用。一定要慎用
这种方法，因为它很可能会屏蔽掉真正的程序错误，使人无法发现！它也可以用
于打印一行错误信息，然后重新抛出异常（可以使调用者更好的处理异常）</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sys</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;myfile.txt&#39;</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
    <span class="n">i</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">())</span>
<span class="k">except</span> <span class="ne">IOError</span> <span class="k">as</span> <span class="p">(</span><span class="n">errno</span><span class="p">,</span> <span class="n">strerror</span><span class="p">):</span>
    <span class="k">print</span> <span class="s">&quot;I/O error({0}): {1}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">errno</span><span class="p">,</span> <span class="n">strerror</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&quot;Could not convert data to an integer.&quot;</span>
<span class="k">except</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&quot;Unexpected error:&quot;</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">raise</span>
</pre></div>
</div>
<p>The <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> ... <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> statement has an optional <em>else
clause</em>, which, when present, must follow all except clauses.  It is useful for
code that must be executed if the try clause does not raise an exception.  For
example:</p>
<p><a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> ... <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 语句可以带有一个 <em>else 子句</em> ，
该子句只能出现在所有 except 子句之后。当 try 语句没有抛出异常时，需要执行一些代码，可以使用
这个子句。例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s">&#39;r&#39;</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span>
        <span class="k">print</span> <span class="s">&#39;cannot open&#39;</span><span class="p">,</span> <span class="n">arg</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span> <span class="n">arg</span><span class="p">,</span> <span class="s">&#39;has&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()),</span> <span class="s">&#39;lines&#39;</span>
        <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The use of the <a class="reference external" href="../reference/compound_stmts.html#else"><tt class="xref docutils literal"><span class="pre">else</span></tt></a> clause is better than adding additional code to
the <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> clause because it avoids accidentally catching an exception
that wasn&#8217;t raised by the code being protected by the <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> ...
<a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> statement.</p>
<p>使用 <a class="reference external" href="../reference/compound_stmts.html#else"><tt class="xref docutils literal"><span class="pre">else</span></tt></a> 子句比在 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 子句中附加代码要好，因为
这样可以避免 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> ... <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 意外的截获本来不属于
它们保护的那些代码抛出的异常。</p>
<p>When an exception occurs, it may have an associated value, also known as the
exception&#8217;s <em>argument</em>. The presence and type of the argument depend on the
exception type.</p>
<p>发生异常时，可能会有一个附属值，作为异常的 <em>参数</em> 存在。这个参数是否存在、
是什么类型，依赖于异常的类型。</p>
<p>The except clause may specify a variable after the exception name (or tuple).
The variable is bound to an exception instance with the arguments stored in
<tt class="docutils literal"><span class="pre">instance.args</span></tt>.  For convenience, the exception instance defines
<a title="object.__str__" class="reference external" href="../reference/datamodel.html#object.__str__"><tt class="xref docutils literal"><span class="pre">__str__()</span></tt></a> so the arguments can be printed directly without having to
reference <tt class="docutils literal"><span class="pre">.args</span></tt>.</p>
<p>在异常名（列表）之后，也可以为 except 子句指定一个变量。这个变量绑定于
一个异常实例，它存储在 <tt class="docutils literal"><span class="pre">instance.args</span></tt> 的参数中。为了方便起见，异常实例
定义了 <a title="object.__str__" class="reference external" href="../reference/datamodel.html#object.__str__"><tt class="xref docutils literal"><span class="pre">__str__()</span></tt></a> ，这样就可以直接访问过打印参数而不必引用
<tt class="docutils literal"><span class="pre">.args</span></tt> 。</p>
<p>One may also instantiate an exception first before raising it and add any
attributes to it as desired. :</p>
<p>这种做法不受鼓励。相反，更好的做法是给异常传递一个参数（如果要传递多个
参数，可以传递一个元组），把它绑定到 message 属性。一旦异常发生，它会
在抛出前绑定所有指定的属性。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>   <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s">&#39;spam&#39;</span><span class="p">,</span> <span class="s">&#39;eggs&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">inst</span><span class="p">:</span>
<span class="gp">... </span>   <span class="k">print</span> <span class="nb">type</span><span class="p">(</span><span class="n">inst</span><span class="p">)</span>     <span class="c"># the exception instance</span>
<span class="gp">... </span>   <span class="k">print</span> <span class="n">inst</span><span class="o">.</span><span class="n">args</span>      <span class="c"># arguments stored in .args</span>
<span class="gp">... </span>   <span class="k">print</span> <span class="n">inst</span>           <span class="c"># __str__ allows args to printed directly</span>
<span class="gp">... </span>   <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">inst</span>          <span class="c"># __getitem__ allows args to be unpacked directly</span>
<span class="gp">... </span>   <span class="k">print</span> <span class="s">&#39;x =&#39;</span><span class="p">,</span> <span class="n">x</span>
<span class="gp">... </span>   <span class="k">print</span> <span class="s">&#39;y =&#39;</span><span class="p">,</span> <span class="n">y</span>
<span class="gp">...</span>
<span class="go">&lt;type &#39;exceptions.Exception&#39;&gt;</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">x = spam</span>
<span class="go">y = eggs</span>
</pre></div>
</div>
<p>If an exception has an argument, it is printed as the last part (&#8216;detail&#8217;) of
the message for unhandled exceptions.</p>
<p>对于未处理的异常，如果它有一个参数，那做就会作为错误信息的最后一部分
（“明细”）打印出来。</p>
<p>Exception handlers don&#8217;t just handle exceptions if they occur immediately in the
try clause, but also if they occur inside functions that are called (even
indirectly) in the try clause. For example:</p>
<p>异常处理句柄不止可以处理直接发生在 try 子句中的异常，即使是其中（甚至
是间接）调用的函数，发生了异常，也一样可以处理。例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">this_fails</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">this_fails</span><span class="p">()</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">ZeroDivisionError</span> <span class="k">as</span> <span class="n">detail</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&#39;Handling run-time error:&#39;</span><span class="p">,</span> <span class="n">detail</span>
<span class="gp">...</span>
<span class="go">Handling run-time error: integer division or modulo by zero</span>
</pre></div>
</div>
</div>
<div class="section" id="raising-exceptions">
<span id="tut-raising"></span><h2>8.4. Raising Exceptions 抛出异常<a class="headerlink" href="#raising-exceptions" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference external" href="../reference/simple_stmts.html#raise"><tt class="xref docutils literal"><span class="pre">raise</span></tt></a> statement allows the programmer to force a specified
exception to occur. For example:</p>
<p>程序员可以用 <a class="reference external" href="../reference/simple_stmts.html#raise"><tt class="xref docutils literal"><span class="pre">raise</span></tt></a> 语句强制指定的异常发生。例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s">&#39;HiThere&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">NameError</span>: <span class="n-Identifier">HiThere</span>
</pre></div>
</div>
<p>The sole argument to <a class="reference external" href="../reference/simple_stmts.html#raise"><tt class="xref docutils literal"><span class="pre">raise</span></tt></a> indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that
derives from <tt class="xref docutils literal"><span class="pre">Exception</span></tt>).</p>
<p>要抛出的异常由 <a class="reference external" href="../reference/simple_stmts.html#raise"><tt class="xref docutils literal"><span class="pre">raise</span></tt></a> 的唯一参数标识。它必需是一个异常实例或
异常类（继承自 <tt class="xref docutils literal"><span class="pre">Exception</span></tt> 的类）。</p>
<p>If you need to determine whether an exception was raised but don&#8217;t intend to
handle it, a simpler form of the <a class="reference external" href="../reference/simple_stmts.html#raise"><tt class="xref docutils literal"><span class="pre">raise</span></tt></a> statement allows you to
re-raise the exception:</p>
<p>如果你需要明确一个异常是否抛出，但不想处理它， <a class="reference external" href="../reference/simple_stmts.html#raise"><tt class="xref docutils literal"><span class="pre">raise</span></tt></a>
语句可以让你很简单的重新抛出该异常。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s">&#39;HiThere&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&#39;An exception flew by!&#39;</span>
<span class="gp">... </span>    <span class="k">raise</span>
<span class="gp">...</span>
<span class="go">An exception flew by!</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n-Identifier">?</span>
<span class="nc">NameError</span>: <span class="n-Identifier">HiThere</span>
</pre></div>
</div>
</div>
<div class="section" id="user-defined-exceptions">
<span id="tut-userexceptions"></span><h2>8.5. User-defined Exceptions 用户自定义异常<a class="headerlink" href="#user-defined-exceptions" title="Permalink to this headline">¶</a></h2>
<p>Programs may name their own exceptions by creating a new exception class (see
<a class="reference external" href="classes.html#tut-classes"><em>Classes 类</em></a> for more about Python classes).  Exceptions should typically
be derived from the <a title="exceptions.Exception" class="reference external" href="../library/exceptions.html#exceptions.Exception"><tt class="xref docutils literal"><span class="pre">Exception</span></tt></a> class, either directly or indirectly.  For
example:</p>
<p>在程序中可以通过创建新的异常类型来命名自己的异常（Python 类的内容请参
见 <a class="reference external" href="classes.html#tut-classes"><em>Classes 类</em></a> ）。异常类通常应该直接或间接的从
<a title="exceptions.Exception" class="reference external" href="../library/exceptions.html#exceptions.Exception"><tt class="xref docutils literal"><span class="pre">Exception</span></tt></a> 类派生，例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">raise</span> <span class="n">MyError</span><span class="p">(</span><span class="mi">2</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="n">MyError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&#39;My exception occurred, value:&#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">value</span>
<span class="gp">...</span>
<span class="go">My exception occurred, value: 4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="n">MyError</span><span class="p">(</span><span class="s">&#39;oops!&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">__main__.MyError</span>: <span class="n-Identifier">&#39;oops!&#39;</span>
</pre></div>
</div>
<p>In this example, the default <a title="object.__init__" class="reference external" href="../reference/datamodel.html#object.__init__"><tt class="xref docutils literal"><span class="pre">__init__()</span></tt></a> of <tt class="xref docutils literal"><span class="pre">Exception</span></tt> has been
overridden.  The new behavior simply creates the <em>value</em> attribute.  This
replaces the default behavior of creating the <em>args</em> attribute.</p>
<p>在这个例子中，:class:<cite>Exception</cite> 默认的 <a title="object.__init__" class="reference external" href="../reference/datamodel.html#object.__init__"><tt class="xref docutils literal"><span class="pre">__init__()</span></tt></a> 被覆盖。新的方式简单的创建
value 属性。这就替换了原来创建 <em>args</em> 属性的方式。</p>
<p>Exception classes can be defined which do anything any other class can do, but
are usually kept simple, often only offering a number of attributes that allow
information about the error to be extracted by handlers for the exception.  When
creating a module that can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and subclass that
to create specific exception classes for different error conditions:</p>
<p>异常类中可以定义任何其它类中可以定义的东西，但是通常为了保持简单，只在
其中加入几个属性信息，以供异常处理句柄提取。如果一个新创建的模块中需要
抛出几种不同的错误时，一个通常的作法是为该模块定义一个异常基类，然后针
对不同的错误类型派生出对应的异常子类。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Error</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Base class for exceptions in this module.&quot;&quot;&quot;</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">InputError</span><span class="p">(</span><span class="n">Error</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Exception raised for errors in the input.</span>

<span class="sd">    Attributes:</span>
<span class="sd">        expr -- input expression in which the error occurred</span>
<span class="sd">        msg  -- explanation of the error</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">expr</span><span class="p">,</span> <span class="n">msg</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">expr</span> <span class="o">=</span> <span class="n">expr</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">msg</span> <span class="o">=</span> <span class="n">msg</span>

<span class="k">class</span> <span class="nc">TransitionError</span><span class="p">(</span><span class="n">Error</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Raised when an operation attempts a state transition that&#39;s not</span>
<span class="sd">    allowed.</span>

<span class="sd">    Attributes:</span>
<span class="sd">        prev -- state at beginning of transition</span>
<span class="sd">        next -- attempted new state</span>
<span class="sd">        msg  -- explanation of why the specific transition is not allowed</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">prev</span><span class="p">,</span> <span class="nb">next</span><span class="p">,</span> <span class="n">msg</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">prev</span> <span class="o">=</span> <span class="n">prev</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">next</span> <span class="o">=</span> <span class="nb">next</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">msg</span> <span class="o">=</span> <span class="n">msg</span>
</pre></div>
</div>
<p>Most exceptions are defined with names that end in &#8220;Error,&#8221; similar to the
naming of the standard exceptions.</p>
<p>与标准异常相似，大多数异常的命名都以“Error”结尾。</p>
<p>Many standard modules define their own exceptions to report errors that may
occur in functions they define.  More information on classes is presented in
chapter <a class="reference external" href="classes.html#tut-classes"><em>Classes 类</em></a>.</p>
<p>很多标准模块中都定义了自己的异常，用以报告在他们所定义的函数中可能发生
的错误。关于类的进一步信息请参见 <a class="reference external" href="classes.html#tut-classes"><em>Classes 类</em></a> 一章。</p>
</div>
<div class="section" id="defining-clean-up-actions">
<span id="tut-cleanup"></span><h2>8.6. Defining Clean-up Actions 定义清理行为<a class="headerlink" href="#defining-clean-up-actions" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement has another optional clause which is intended to
define clean-up actions that must be executed under all circumstances.  For
example:</p>
<p><a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句还有另一个可选的子句，目的在于定义在任何情况下都一定要执行的功
能。例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">raise</span> <span class="ne">KeyboardInterrupt</span>
<span class="gp">... </span><span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&#39;Goodbye, world!&#39;</span>
<span class="gp">...</span>
<span class="go">Goodbye, world!</span>
<span class="nc">KeyboardInterrupt</span>
</pre></div>
</div>
<p>A <em>finally clause</em> is always executed before leaving the <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a>
statement, whether an exception has occurred or not. When an exception has
occurred in the <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> clause and has not been handled by an
<a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> clause (or it has occurred in a <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> or
<a class="reference external" href="../reference/compound_stmts.html#else"><tt class="xref docutils literal"><span class="pre">else</span></tt></a> clause), it is re-raised after the <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> clause has
been executed.  The <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> clause is also executed &#8220;on the way out&#8221;
when any other clause of the <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement is left via a
<a class="reference external" href="../reference/simple_stmts.html#break"><tt class="xref docutils literal"><span class="pre">break</span></tt></a>, <a class="reference external" href="../reference/simple_stmts.html#continue"><tt class="xref docutils literal"><span class="pre">continue</span></tt></a> or <a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> statement.  A more
complicated example (having <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> and <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> clauses in
the same <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement works as of Python 2.5):</p>
<p>不管有没有发生异常， <em>finally 子句</em> 在程序离开 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 后都一定
会被执行。当 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句中发生了未被 <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 捕获的
异常（或者它发生在 <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 或 <a class="reference external" href="../reference/compound_stmts.html#else"><tt class="xref docutils literal"><span class="pre">else</span></tt></a> 子句中），在
<a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> 子句执行完后它会被重新抛出。 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句经
由 <a class="reference external" href="../reference/simple_stmts.html#break"><tt class="xref docutils literal"><span class="pre">break</span></tt></a> ，:keyword:<cite>continue</cite> 或 <a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> 语句退
出也一样会执行 <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> 子句。以下是一个更复杂些的例子（在同
一个 <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> 语句中的 <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 和 <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a>
子句的工作方式与 Python 2.5 一样）</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">divide</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">/</span> <span class="n">y</span>
<span class="gp">... </span>    <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="s">&quot;division by zero!&quot;</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="s">&quot;result is&quot;</span><span class="p">,</span> <span class="n">result</span>
<span class="gp">... </span>    <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="s">&quot;executing finally clause&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">result is 2</span>
<span class="go">executing finally clause</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">division by zero!</span>
<span class="go">executing finally clause</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="s">&quot;2&quot;</span><span class="p">,</span> <span class="s">&quot;1&quot;</span><span class="p">)</span>
<span class="go">executing finally clause</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">3</span>, in <span class="n-Identifier">divide</span>
<span class="nc">TypeError: unsupported operand type(s) for /</span>: <span class="n-Identifier">&#39;str&#39; and &#39;str&#39;</span>
</pre></div>
</div>
<p>As you can see, the <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> clause is executed in any event.  The
<a title="exceptions.TypeError" class="reference external" href="../library/exceptions.html#exceptions.TypeError"><tt class="xref docutils literal"><span class="pre">TypeError</span></tt></a> raised by dividing two strings is not handled by the
<a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> clause and therefore re-raised after the <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a>
clause has been executed.</p>
<p>如你所见， <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> 子句在任何情况下都会执
行。 <a title="exceptions.TypeError" class="reference external" href="../library/exceptions.html#exceptions.TypeError"><tt class="xref docutils literal"><span class="pre">TypeError</span></tt></a>
在两个字符串相除的时候抛出，未被 <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> 子句捕获，因此在
<a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> 子句执行完毕后重新抛出。</p>
<p>In real world applications, the <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> clause is useful for
releasing external resources (such as files or network connections), regardless
of whether the use of the resource was successful.</p>
<p>在真实场景的应用程序中， <a class="reference external" href="../reference/compound_stmts.html#finally"><tt class="xref docutils literal"><span class="pre">finally</span></tt></a> 子句用于释放外部资源（文件
或网络连接之类的），无论它们的使用过程中是否出错。</p>
</div>
<div class="section" id="predefined-clean-up-actions">
<span id="tut-cleanup-with"></span><h2>8.7. Predefined Clean-up Actions 预定义清理行为<a class="headerlink" href="#predefined-clean-up-actions" title="Permalink to this headline">¶</a></h2>
<p>Some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. Look at the following example, which tries to open a file
and print its contents to the screen. :</p>
<p>有些对象定义了标准的清理行为，无论对象操作是否成功，不再需要该对象的时
候就会起作用。以下示例尝试打开文件并把内容打印到屏幕上。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s">&quot;myfile.txt&quot;</span><span class="p">):</span>
    <span class="k">print</span> <span class="n">line</span>
</pre></div>
</div>
<p>The problem with this code is that it leaves the file open for an indeterminate
amount of time after the code has finished executing. This is not an issue in
simple scripts, but can be a problem for larger applications. The
<a class="reference external" href="../reference/compound_stmts.html#with"><tt class="xref docutils literal"><span class="pre">with</span></tt></a> statement allows objects like files to be used in a way that
ensures they are always cleaned up promptly and correctly. :</p>
<p>这段代码的问题在于在代码执行完后没有立即关闭打开的文件。这在简单的脚本
里没什么，但是大型应用程序就会出问题。 <a class="reference external" href="../reference/compound_stmts.html#with"><tt class="xref docutils literal"><span class="pre">with</span></tt></a> 语句使得文件之类的对象可以
确保总能及时准确地进行清理。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">&quot;myfile.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="k">print</span> <span class="n">line</span>
</pre></div>
</div>
<p>After the statement is executed, the file <em>f</em> is always closed, even if a
problem was encountered while processing the lines. Other objects which provide
predefined clean-up actions will indicate this in their documentation.</p>
<p>语句执行后，文件 <em>f</em> 总会被关闭，即使是在处理文件中的数据时出错也一样。
其它对象是否提供了预定义的清理行为要查看它们的文档。</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">8. Errors and Exceptions 错误和异常</a><ul>
<li><a class="reference external" href="#syntax-errors">8.1. Syntax Errors 语法错误</a></li>
<li><a class="reference external" href="#exceptions">8.2. Exceptions</a></li>
<li><a class="reference external" href="#handling-exceptions">8.3. Handling Exceptions 控制异常</a></li>
<li><a class="reference external" href="#raising-exceptions">8.4. Raising Exceptions 抛出异常</a></li>
<li><a class="reference external" href="#user-defined-exceptions">8.5. User-defined Exceptions 用户自定义异常</a></li>
<li><a class="reference external" href="#defining-clean-up-actions">8.6. Defining Clean-up Actions 定义清理行为</a></li>
<li><a class="reference external" href="#predefined-clean-up-actions">8.7. Predefined Clean-up Actions 预定义清理行为</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="inputoutput.html"
                                  title="previous chapter">7. Input and Output 输入和输出</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="classes.html"
                                  title="next chapter">9. Classes 类</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/tutorial/errors.txt"
         rel="nofollow">Show Source</a></li>
</ul>

          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="classes.html" title="9. Classes 类"
             >next</a> |</li>
        <li class="right" >
          <a href="inputoutput.html" title="7. Input and Output 输入和输出"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2010, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 04, 2010.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.5.
    </div>

  </body>
</html>